package com.tanhua.app.controllerservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.TanHuaUserApi;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLove;
import com.tanhua.domain.mongo.UserNlove;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.TodayBest;
import com.tanhua.domain.vo.UserHolder;
import com.tanhua.template.HuanXinTemplate;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.springframework.http.ResponseEntity.ok;
import java.util.*;

@Service
public class TanHuaService {


    @Reference
    private RecommendUserApi recommendUserApi;


    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private FriendsApi friendsApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private QuanZiService quanZiService;

    @Reference
    private TanHuaUserApi tanHuaUserApi;

    @Autowired
    private BaiduService baiduService;



    public ResponseEntity todayBest() {

        // 1 根据当前登录用户的id查询缘分值最高的女神id （mongoDB）
        RecommendUser recommendUser = recommendUserApi.findBytodayBest(UserHolder.getUser().getId());
        //2 根据女神的id去userInfo表中查询女神的信息  (mysql)
        UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());
/*        RecommendUser recommendUser = recommendUserApi.findBytodayBest(UserHolder.getUser().getId());*/

        //模拟数据 没有缘分人都是2号
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L); //在这里是写死的  你可以做成随机的
            recommendUser.setScore(99.0); //这里的得分也是写死的
        }
/*        //2 根据女神的id去userInfo表中查询女神的信息  (mysql)
        UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());*/

        //3 将女生信息和缘分值封装到vo中
        TodayBest todayBest = new TodayBest();
        todayBest.setFateValue(recommendUser.getScore().longValue());
        BeanUtil.copyProperties(userInfo, todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        return ok(todayBest);
    }

    public ResponseEntity recommendation(Integer page, Integer pagesize) {

        //1 分页查询女神的id和缘分值
        PageBeanVo pageBean = recommendUserApi.findRecommendation(page, pagesize, UserHolder.getUser().getId());
        List<RecommendUser> items = (List<RecommendUser>) pageBean.getItems();

        // 没有佳人（假数据）
        if (items.size() == 0) {
            items = fromtuijianren();
        }


        List<TodayBest> list = new ArrayList<TodayBest>();
        //有佳人
        if (CollectionUtil.isNotEmpty(items)) {
            //2 根据女神id查询女神信息
            for (RecommendUser recommendUser : items) {
                UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());

                //3 将女神信息和缘分值封装给vo
                TodayBest todayBest = new TodayBest();
                BeanUtil.copyProperties(userInfo, todayBest);
                todayBest.setTags(userInfo.getTags().split(","));

                todayBest.setFateValue(recommendUser.getScore().longValue());

                list.add(todayBest);
            }
        }

        //4 将vo数据给pageBean
        pageBean.setItems(list);

        //5 返回pageBean
        return ok(pageBean);
    }


    private List<RecommendUser> fromtuijianren() {
        List<RecommendUser> list = new ArrayList<RecommendUser>();

        for (Long i = 1l; i <= 10; i++) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(60, 99));
            list.add(recommendUser);
        }
        return list;
    }

    public ResponseEntity personalInfo(Integer jrid) {

        //根据佳人id查询佳人的信息
        UserInfo userInfo = userInfoApi.findUserInfo(jrid.longValue());
        //根据佳人id和当前登录用户查询2者之间的缘分值 recommend_user
        RecommendUser user = recommendUserApi.findScore(jrid, UserHolder.getUser().getId());
        if (user == null) {
            user = new RecommendUser();
            user.setScore(99d); //假收据
        }
        // 封装佳人信息和当前登录用户之间的缘分值 给app
        TodayBest todayBest = new TodayBest();
        BeanUtil.copyProperties(userInfo, todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setFateValue(user.getScore().longValue());

        return ok(todayBest);
    }

    public ResponseEntity strangerQuestions(Integer userId) {

        //带着userId查询问题表
        Question question = questionApi.findQuestion(userId.longValue());

        if (question == null) {
            question = new Question();
            question.setStrangerQuestion("你是GG还是MM？");
        }

        return ok(question.getStrangerQuestion());

    }

    public ResponseEntity toStrangerQuestions(Integer userId, String info) {

        //当前登录用户
        UserInfo userInfo = userInfoApi.findUserInfo(UserHolder.getUser().getId());

        //拼装环信要的数据
        Map<String, String> hxMap = new HashMap<>(); //bug: 环信要求的key value都是String
        hxMap.put("userId", userInfo.getId().toString());
        hxMap.put("nickname", userInfo.getNickname());
        //根据佳人的id获取佳人的问题
        Question question = questionApi.findQuestion(userId.longValue());
        hxMap.put("strangerQuestion", question.getStrangerQuestion());
        hxMap.put("reply", info);

        //map转换成json数据给环信
        String json = JSON.toJSONString(hxMap);
        //调用环信方法发送验证消息
        huanXinTemplate.sendMsg(userId.toString(), json);


        return ok(null);
    }

    public ResponseEntity<String> like(Long userId, Long otherUserId) {
        // 1. 是好友
        // 2. 我喜欢他
        //     不处理
        final Boolean isFriend = friendsApi.isFriends(userId.intValue(), otherUserId);
        final boolean iLikeOther = userLikeApi.isFirstUserLikeLastUser(userId, otherUserId);
        if (isFriend || iLikeOther) {
            return ok("不用处理");
        }
        // 3. 他喜欢我
        //     双方加为好友
        //         删除他喜欢我的记录，添加好友记录
        final boolean otherLikeMe = userLikeApi.isFirstUserLikeLastUser(otherUserId, userId);
        if (otherLikeMe) {
            userLikeApi.deleteFirstUserLikeLastUser(otherUserId, userId);
            friendsApi.contacts(userId.intValue(), otherUserId);
            return ok("已经添加为好友");
        }
        // 4. 无关系
        //     变为我喜欢他
        //         添加我喜欢他的记录
        userLikeApi.addFirstUserLikeLastUser(userId, otherUserId);
        return ok("已经喜欢该用户");
    }

    public ResponseEntity<String> dislike(Long userId, Long otherUserId) {
        // 1. 是好友
        //     变为他喜欢我
        //         删除好友记录，添加他喜欢我的记录
        final Boolean isFriend = friendsApi.isFriends(userId.intValue(), otherUserId);
        if (isFriend) {
            friendsApi.deleteFriends(userId, otherUserId.intValue());
            userLikeApi.addFirstUserLikeLastUser(otherUserId, userId);
            return ok("不喜欢该用户，已经不是好友");
        }

        // 2. 我喜欢他
        //     变为无关系
        //         删除我喜欢他的记录
        final boolean iLikeOther = userLikeApi.isFirstUserLikeLastUser(userId, otherUserId);
        if (iLikeOther) {
            userLikeApi.deleteFirstUserLikeLastUser(userId, otherUserId);
            return ok("不喜欢该用户，已经不是该用户粉丝");
        }
        // 3. 他喜欢我
        // 4. 无关系
        //     不处理
        return ok("不用处理");
    }


    public List<TodayBest> queryCardsList() {
        User user = UserHolder.getUser();

        //APP探花展示的所有推荐人ID
        HashSet<Long> CardsListId = new HashSet<>();

        //获取用户朋友和已经喜欢的人的ID，进行排除
        HashSet<Long> noShowId = recommendUserApi.findNoShowId(user.getId());

        //添加自己的ID
        noShowId.add(user.getId());

        //获取5个喜欢自己的用户ID，优先展示,优先于大数据推荐,促进配对的成功率，
        List<Long> loveMeUser = tanHuaUserApi.findLoveMeUser(user.getId());
        CardsListId.addAll(loveMeUser);
        //已经添加进展示列表的ID将会被添加到禁止查询的列表，后续其它表中不再查询
        noShowId.addAll(loveMeUser);
        //添加大数据获取推荐人ID,优先级高于后台人工推荐数据
        PageBeanVo pageBeanVo = quanZiService.formRedis(1, 1, user.getId());
        if (pageBeanVo != null) {
            List<Publish> items = (List<Publish>) pageBeanVo.getItems();
            for (Publish item : items) {
                if (!noShowId.contains(item.getUserId())) {
                    CardsListId.add(item.getUserId());
                    //已经添加进展示列表的ID将会被添加到禁止查询的列表，后续其它表中不再查询
                    noShowId.add(item.getUserId());
                }
            }
        }


            //使用后台的推荐数据，后台推荐总数最多20条。（后台推荐主要用于提高会员付费用户的曝光率）
            //会员列表的用户会被放入后台推荐表中，推荐表中被选出的概率要远远大于普通用户（提供的App没有设计会员体系
            //所以不展示，但是此功能已实现，方便以后拓展）
            //推荐列表中应该有性别，但是提供的表中没有，为了不影响其他功能，暂时进行性别排除的方式，效率相对来说比较低！
            int count = 20;
            String UserGender = userInfoApi.findUserInfo(user.getId()).getGender();
            List<RecommendUser> recommendUserList = this.recommendUserApi.queryCardList(user.getId(), count);
            for (RecommendUser recommendUser : recommendUserList) {
                if (userInfoApi.findUserInfo(recommendUser.getUserId()).getGender().equals(UserGender)){
                    CardsListId.add(recommendUser.getUserId());
                    //已经添加进展示列表的ID将会被添加到禁止查询的列表，后续其它表中不再查询
                    noShowId.add(recommendUser.getUserId());
                }

        }

        // 再在所有除了好友和不喜欢的以及已经喜欢的用户之外中随机选择，最多随机50条。
        // 此处不存在大于50条数据的情况，因为之前的查询都有限制条数。
        if (CardsListId != null) {
            int size = CardsListId.size();

            if (size < 50) {
                ArrayList<Integer> RandomUser = recommendUserApi.SelectRandomUserId(noShowId, 50 - size,UserGender);
                for (Integer RandomUserId : RandomUser) {
                    CardsListId.add(RandomUserId.longValue());
                }
            }



        }

        List<UserInfo> userInfoList = new ArrayList<>();
        for (Long aLong : CardsListId) {
            UserInfo userInfo = userInfoApi.findUserInfo(aLong);
            userInfoList.add(userInfo);
        }


        //返回TodayBest是因为前台要求的数据正好和TodayBest中的数据对应，不用再创建表了，省事儿！
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
             BeanUtil.copyProperties(userInfo,todayBest);
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
            todayBest.setFateValue(0L);
            todayBests.add(todayBest);
        }

        return todayBests;

    }

    public void loveUser(Long loveUserId) {
        System.out.println(loveUserId);
        Long Myid = UserHolder.getUser().getId();
        tanHuaUserApi.saveLove(Myid, loveUserId);

    }

    public void DisloveUser(Long disloveUserId) {
        Long Userid = UserHolder.getUser().getId();
        UserNlove userDisLove = new UserNlove();
        userDisLove.setNloveUserId(disloveUserId);
        userDisLove.setUserId(Userid);
        tanHuaUserApi.saveNlove(userDisLove);

    }



}
